package com.baijiaoxi.common.utils.jdk;

import com.baijiaoxi.common.utils.jdk.model.CMDResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.*;

/**
 * Created by shixj on 2018/3/16.
 */
@Slf4j
public class CMDUtil {

    public static CMDResponse runWithResult(String cmd) {
        CMDResponse cmdResponse = null;
        StringBuilder res = new StringBuilder("");
        Runtime rt = Runtime.getRuntime();
        try {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            log.debug("run : " + cmd);
            Process pr = rt.exec(cmd); // cmd /c calc
            Callable<CMDResponse> myCallable = new Callable() {
                @Override
                public CMDResponse call() throws Exception {
                    BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));
                    String line = null;
                    while ((line = input.readLine()) != null) {
                        res.append(line);
                    }
                    int exitVal = pr.waitFor();
                    return new CMDResponse(res.toString(), String.valueOf(exitVal));
                }
            };
            log.debug("call wait ");
            Future<CMDResponse> future = executor.submit(myCallable);
            try {
                cmdResponse = future.get(5, TimeUnit.SECONDS);
            } catch (Exception e) {
                pr.destroyForcibly();
                log.error("runWithResult fail:" + cmd, e);
                cmdResponse = new CMDResponse(res.toString(), "-1");
            } finally {
                executor.shutdown();
            }
        } catch (Exception e) {
            log.error("runWithResult fail:" + cmd, e);
        }
        return cmdResponse;
    }

    public static void runWithoutResult(String cmd) {
        try {
            Runtime rt = Runtime.getRuntime();
            rt.exec(cmd); // cmd /c calc
        } catch (Exception e) {
            log.error("命令执行失败", e);
        }
    }
}
